package com.appkubes.mall.restful.application.common.sms.service.impl;

import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.core.entity.MallSmsCode;
import com.appkubes.mall.core.service.impl.BaseMallSmsCodeServiceImpl;
import com.appkubes.mall.restful.application.common.sms.entity.vo.CodeVO;
import com.appkubes.mall.restful.application.common.sms.entity.vo.TelVo;
import com.appkubes.mall.restful.application.common.sms.service.CodeService;
import com.appkubes.mall.restful.application.user.user.dao.CodeDao;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CodeServiceImpl extends BaseMallSmsCodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;


    public List<MallSmsCode> getList(String queryStr) {
        return codeDao.getList(queryStr);
    }



    @Override
    public CodeDao getCodeDao() {
        return codeDao;
    }

    @Override
    public Boolean addCode(CodeVO codeVO) {
        MallSmsCode mallSmsCode = new MallSmsCode();
        mallSmsCode.setCode(codeVO.getCode());
        mallSmsCode.setTel(codeVO.getTel());
        mallSmsCode.setIsUse(0);
        mallSmsCode.setType(0);
        mallSmsCode.setCreateTime(DateUtils.DateToTimestamp(new Date()));
        mallSmsCode.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
        mallSmsCode.setCodeKey(UUIDUtils.getUUID());
        mallSmsCode.setAppKey(null);
        return this.save(mallSmsCode);
    }

    @Override
    public MallSmsCode getSmsSurvivor(TelVo telVo) {
        QueryWrapper<MallSmsCode> queryWrapper = new QueryWrapper<>();
        MallSmsCode mallSmsCode = new MallSmsCode();
        mallSmsCode.setTel(telVo.getTel());
        queryWrapper.eq("is_use", 0); // 未被使用的验证码
        queryWrapper.ge("create_time", DateUtils.DateToTimestamp(new Date()) - 60);
        queryWrapper.setEntity(mallSmsCode);
        MallSmsCode code = getOne(queryWrapper);
        return code;
    }

    @Override
    public MallSmsCode getSmsSurvivor(CodeVO codeVO) {
        QueryWrapper<MallSmsCode> queryWrapper = new QueryWrapper<>();
        MallSmsCode mallSmsCode = new MallSmsCode();
        mallSmsCode.setTel(codeVO.getTel());
        mallSmsCode.setCode(codeVO.getCode());
        queryWrapper.eq("is_use", 0); // 未被使用的验证码
        queryWrapper.ge("create_time", DateUtils.DateToTimestamp(new Date()) - 60);
        queryWrapper.setEntity(mallSmsCode);
        MallSmsCode code = getOne(queryWrapper);
        return code;
    }

    @Override
    public Boolean smsDie(MallSmsCode mallSmsCode) {
        mallSmsCode.setIsUse(1);
        mallSmsCode.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
        return updateById(mallSmsCode);
    }
}
